<?php
    require_once ('global.php');
    require_once ('usuario.php');
    require_once ('SmartyReady.php');
    // preparem la sessio
    session_start();
    // preparem l'smarty
    $sm = new SmartyReady();
    $sm->muntarTemplates();
    $sm->assign('banner','buit.tpl');
    $sm->assign('cuerpo','buit.tpl');
    if (empty($_SESSION['username'])) {
        if(!empty($_POST['login_usuario']) && !empty($_POST['login_pass'])) {
            $pass = "lulz"; // pas x defecte xD 
            try  {
                $luser = Usuario::findByUsername($_POST['login_usuario']);
                $pass = $luser->get_password();
            } 
            catch (Exception $e) {}
            // Codifiquem la pass i fem comparacions i redirigim segons calgui
            if (md5(SALT . $_POST['login_pass'] . SALT) == $pass) {
                $sm->assign('resultatLogin','Login ok');
                $_SESSION['username'] = $luser->get_username();
                $_SESSION['pass'] = $pass;
                $_SESSION['avatar'] = $luser->get_avatar();
                ?><meta http-equiv="Refresh" content="0;url=./perfil.php"><?php
            }
            else  {
                $sm->assign('banner','login.tpl');
                $sm->assign('resultatLogin','login incorrecte');
                ?><meta http-equiv="Refresh" content="2;url=./index.php"><?php
            }
        }
        else {
            $sm->assign('banner','login.tpl');
            $sm->assign('resultatLogin','falten dades');
            ?><meta http-equiv="Refresh" content="2;url=./index.php"><?php
        }
    }
    else {
        if (!empty($_POST['logout'])) {
            // Destruim la sessio
            unset($_SESSION);
            session_destroy();
            $sm->assign('banner','login.tpl');
            $sm->assign('resultatLogin','');
            ?><meta http-equiv="Refresh" content="0;url=./index.php"><?php
        }
    }
    $sm->display("E:/wamp/www/JediMusic/Smarty/templates/base.tpl");
?>
